﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace HBFramework
{
    /// <summary>
    /// csharp工具类
    /// </summary>
    public class CSUtility
    {
        /// <summary>
        /// 获取所有子类
        /// </summary>
        /// <param name="baseType"></param>
        /// <returns></returns>
        public static List<Type> GetSubclasses(Type baseType)
        {
            // 获取当前域中所有已加载的程序集
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            // 存储所有子类的列表
            List<Type> subclasses = new List<Type>();

            // 遍历每个程序集
            foreach (Assembly assembly in assemblies)
            {
                // 获取程序集中定义的所有类型
                Type[] types = assembly.GetTypes();

                // 遍历每个类型
                foreach (Type type in types)
                {
                    // 检查类型父类是否是泛型类型
                    if (type.BaseType != null && type.BaseType.IsGenericType)
                    {
                        // 检查类型是否是指定泛型父类的子类
                        if (type.BaseType.GetGenericTypeDefinition() == baseType)
                        {
                            subclasses.Add(type);
                        }
                    }
                    // 检查类型是否是指定基类的子类
                    else if (type.IsSubclassOf(baseType))
                    {
                        subclasses.Add(type);
                    }
                }
            }

            return subclasses;
        }

        /// <summary>
        /// 获取带有标签的所有类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Type[] GetClassWithAttirbute<T>() where T:Attribute
        {
            List<Type> result = new List<Type>();
            var asm = Assembly.GetExecutingAssembly();
            Type[] types = asm.GetTypes().ToArray();
            foreach (Type tt in types)
            {
                var attributes = tt.GetCustomAttributes<T>().ToList();
                if (attributes == null)
                    continue;
                for (int i = 0; i < attributes.Count; i++)
                {
                    if(attributes[i] is T)
                    {
                        result.Add(tt);
                        break;
                    }
                }
            }
            return result.ToArray();
        }
    }
}